//
//  NSObject+JsonKit.m
//  ISA
//
//  Created by zhoumeineng on 2018/5/8.
//  Copyright © 2018年 zhoumeineng. All rights reserved.
//

#import "NSObject+JsonKit.h"
#import <objc/runtime.h>
#import <objc/message.h>
@implementation NSObject (JsonKit)
+(id)dictionary_objc:(NSDictionary*)dic{
    Class cls = [self class];
    NSObject * objct = [[cls alloc]init];
    while (1) {
        
        if ([cls isEqual:[NSObject class]]) {
            break;
        }
        /**
         * 赋值 两种情况 1： 字典参数>objec的属性个数 先遍历的object  2：objec的属性个数>字典参数
         * 这里选择 遍历的是object的属性
         */
        unsigned int outCount = 0;
        Ivar * ivar = class_copyIvarList(cls, &outCount);
        cls = [cls superclass];
        if (ivar==NULL) {
            continue;
        }
        for (Ivar *var = ivar; var<ivar+outCount; ++var) {
            const Ivar  p = *var;
            const char * name =  ivar_getName(p);
            NSString * key = [[NSString stringWithUTF8String:name] stringByReplacingOccurrencesOfString:@"_" withString:@""];
            name = [key UTF8String];
            if ([[dic allKeys] containsObject:[NSString stringWithUTF8String:name]]) {
                object_setIvar(objct, p, [dic valueForKey:[NSString stringWithUTF8String:name]]);
            }
        }
    }
    return objct;
}

+(id)array_objc:(NSArray *)array{
    NSMutableArray * mut = [[NSMutableArray alloc]init];
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[NSDictionary class]]) {
          NSObject * ob = [self dictionary_objc:obj];
            if (ob!=nil) {
                [mut addObject:ob];
            }
        }
    }];
    return mut;
}

+(NSDictionary*)objc_dictionary:(id)object{
    NSMutableDictionary * dict = [[NSMutableDictionary alloc]init];
    Class cls = [self class];
    id result = nil;
    if ([object isKindOfClass:[NSObject class]]) {
        while (1) {
            if ([cls isEqual:[NSObject class]]) {
                break;
            }
            unsigned int outCount = 0;
            Ivar * ivar = class_copyIvarList(cls, &outCount);
            cls = [cls superclass];
            if (ivar==NULL) {
                continue;
            }
            for (Ivar *var = ivar; var<ivar+outCount; ++var) {
                const Ivar  p = *var;
                const char * name =  ivar_getName(p);
                NSString * key = [[NSString stringWithUTF8String:name] stringByReplacingOccurrencesOfString:@"_" withString:@""];
                result = [object valueForKey:key];
                if (result==nil) {//当为空的时候 跳过
                    continue;
                }
                [dict setValue:result forKey:key];
            }
        }
    }
    return dict;
}
@end
